package com.zd.commodity.userMng.biz.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.zd.commodity.biz.impl.BaseBiz;
import com.zd.commodity.userMng.biz.IMmenuBiz;
import com.zd.commodity.userMng.dao.IMmenuDao;
import com.zd.commodity.userMng.dao.IRoleDao;
import com.zd.commodity.userMng.entity.Mmenu;
import com.zd.commodity.userMng.entity.Role;
import com.zd.commodity.userMng.entity.State;
@Service
public class MmenuBiz extends BaseBiz<Mmenu> implements IMmenuBiz {
	
	private IMmenuDao mmenuDao;
	@Autowired
	private IRoleDao roleDao;
	
	
	//获取修改角色的菜单列表
	public List<Mmenu> getRoleMenuListToUpdate(Long rid){
		Role role = roleDao.get(rid);
		List<Mmenu> roleSecondMenus = role.getMenus();//角色拥有的二级菜单
		Mmenu allMmenu = mmenuDao.get((long) 0);
		List<Mmenu> roleMenus = new ArrayList<Mmenu>();
		//遍历1级菜单
		for(Mmenu menu1:allMmenu.getNodes()){
			
			boolean menu1Check = false;
			//2级菜单
			for(Mmenu menu2 : menu1.getNodes()){
				if(roleSecondMenus.contains(menu2)){
					menu2 = checkMenu(menu2);
					menu1Check = true;
				}
				menu2.setTags(new Long[]{menu2.getId()});
				menu2.setNodes(null);
			}
			if(menu1Check){
				menu1 = checkMenu(menu1);
			}
			menu1.setTags(new Long[]{menu1.getId()});
			roleMenus.add(menu1);
		}
		return roleMenus;
	}
	
	//选中菜单
	private Mmenu checkMenu(Mmenu menu){
		State state = new State();
		state.setChecked(true);
		menu.setState(state);
		return menu;
	}
	
	//复制菜单的方法
	private Mmenu copyMenu(Mmenu menu){
		Mmenu m = new Mmenu();
		m.setText(menu.getText());
		m.setHref(menu.getHref());
		m.setNodes(new ArrayList());
		return m;
	}
	//获取角色菜单
	public List<Mmenu> getRoleMenu(Long rid){
		Role role = roleDao.get(rid);
		List<Mmenu> secondRoleMenus = role.getMenus();
		Mmenu AllMmenu = mmenuDao.get((long) 0);
		List<Mmenu> roleMenus = new ArrayList<Mmenu>();
		//遍历1级菜单
		for(Mmenu menu1:AllMmenu.getNodes()){
			Mmenu m1 = copyMenu(menu1);
			//2级菜单
			for(Mmenu menu2 : menu1.getNodes()){
				if(secondRoleMenus.contains(menu2)){
					Mmenu m2 = copyMenu(menu2);
					m2.setNodes(null);
					List<Mmenu> nodes = m1.getNodes();
					m1.getNodes().add(m2);
				}
			}
			if(m1.getNodes().size()>0){
				roleMenus.add(m1);
			}
		}
		return roleMenus;
	}
	@Autowired
	public void setMmenuDao(IMmenuDao mmenuDao) {
		this.mmenuDao = mmenuDao;
		this.setBaseDao(mmenuDao);
	}

	public IRoleDao getRoleDao() {
		return roleDao;
	}

	public void setRoleDao(IRoleDao roleDao) {
		this.roleDao = roleDao;
	}

}
